package edu.guigu.networkdemomvvm.nonsingle;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.databinding.BindingAdapter;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ObservableArrayList;
import androidx.lifecycle.ViewModel;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;

import java.util.List;

import edu.guigu.networkdemomvvm.nonsingle.User;
import edu.guigu.networkdemomvvm.R;
import edu.guigu.networkdemomvvm.databinding.ItemUserBinding;

public class StateViewModel extends ViewModel {

    public final ObservableArrayList<User> userList = new ObservableArrayList<>();

    public void addUser(User user) {
        userList.add(user);
    }

    public void addUserList(List<User> users) {
        userList.addAll(users);
    }

    @BindingAdapter("android:entries")
    public static void setEntries(RecyclerView recyclerView, ObservableArrayList<User> userList) {
        UserListAdapter adapter = (UserListAdapter) recyclerView.getAdapter();
        // 如是首次绑定，则创建adapter，设置绑定
        if (adapter == null) {
            adapter = new UserListAdapter(userList);
            recyclerView.setAdapter(adapter);
        }
        // 如不是首次绑定，则更新数据
        else {
            adapter.notifyDataSetChanged();
        }
    }

    static class UserListAdapter extends RecyclerView.Adapter<UserListAdapter.ViewHolder> {

        private final ObservableArrayList<User> userList;

        public UserListAdapter(ObservableArrayList<User> userList) {
            this.userList = userList;
        }

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            LayoutInflater inflater = LayoutInflater.from(parent.getContext());
            ItemUserBinding binding = DataBindingUtil.inflate(inflater, R.layout.item_user, parent, false);
            return new ViewHolder(binding);
        }

        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
            holder.binding.setUser(userList.get(position));
        }

        @Override
        public int getItemCount() {
            return userList.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            ItemUserBinding binding;

            public ViewHolder(ItemUserBinding binding) {
                super(binding.mainCardView);
                this.binding = binding;
            }
        }
    }
}
